<template>
  <div class="gen-edit-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">代码生成配置</span>
            <div class="header-buttons">
              <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
              <el-button type="info" icon="el-icon-view" @click="handlePreview">预览代码</el-button>
              <el-button type="success" icon="el-icon-download" @click="handleGenCode">生成代码</el-button>
            </div>
          </div>
          
          <div class="tab-container">
            <div class="tab-nav">
              <div 
                class="tab-item" 
                :class="{ 'active': activeTab === 'field' }"
                @click="activeTab = 'field'"
              >
                <div class="tab-icon">
                  <i class="el-icon-tickets"></i>
                </div>
                <div class="tab-text">字段信息</div>
              </div>
              <div 
                class="tab-item" 
                :class="{ 'active': activeTab === 'gen' }"
                @click="activeTab = 'gen'"
              >
                <div class="tab-icon">
                  <i class="el-icon-setting"></i>
                </div>
                <div class="tab-text">生成信息</div>
              </div>
            </div>
            
            <div class="tab-content">
              <div v-show="activeTab === 'field'" class="tab-pane">
                <el-table :data="columns" border stripe>
                  <el-table-column label="序号" type="index" width="50" />
                  <el-table-column label="字段名称" prop="columnName" width="150" />
                  <el-table-column label="字段描述" prop="columnComment" width="150">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.columnComment" placeholder="请输入字段描述" />
                    </template>
                  </el-table-column>
                  <el-table-column label="物理类型" prop="columnType" width="120" />
                  <el-table-column label="Java类型" width="120">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.javaType">
                        <el-option label="Long" value="Long" />
                        <el-option label="String" value="String" />
                        <el-option label="Integer" value="Integer" />
                        <el-option label="Double" value="Double" />
                        <el-option label="BigDecimal" value="BigDecimal" />
                        <el-option label="Date" value="Date" />
                        <el-option label="Boolean" value="Boolean" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="Java属性" width="120">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.javaField" placeholder="请输入Java属性" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-show="activeTab === 'gen'" class="tab-pane">
                <gen-info-form ref="genInfo" :info="info" :tables="tables" :menus="menus" @preview-data="handlePreviewData" />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预览代码对话框 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-tabs v-model="preview.activeName">
            <el-tab-pane
              v-for="(value, key) in preview.data"
              :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
              :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
              :key="key"
            >
              <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
              <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import GenInfoForm from '../gen/genInfoForm'
import { getGenTable, updateGenTable, genCode, previewTable } from '@/api/tool/gen'
import { listMenu as getMenuTreeselect } from '@/api/system/menu'
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

export default {
  name: 'GenEdit',
  components: {
    GenInfoForm
  },
  data() {
    return {
      // 当前激活的标签
      activeTab: 'field',
      // 表详细信息
      info: {},
      // 表列信息
      columns: [],
      // 表信息
      tables: [],
      // 菜单信息
      menus: [],
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      }
    }
  },
  created() {
    const tableId = this.$route.params.tableId
    if (tableId) {
      this.getInfo(tableId)
    }
    this.getMenuTreeselect()
  },
  methods: {
    /** 获取表详细信息 */
    getInfo(tableId) {
      getGenTable(tableId).then(res => {
        this.info = res.data.info
        this.columns = res.data.rows
        this.tables = res.data.tables
      })
    },
    /** 获取菜单下拉树列表 */
    getMenuTreeselect() {
      getMenuTreeselect().then(res => {
        this.menus = res.data
      })
    },
    /** 提交表单 */
    submitForm() {
      const genInfo = this.$refs.genInfo.info
      const formData = {
        ...genInfo,
        columns: this.columns
      }
      
      updateGenTable(formData).then(res => {
        this.$modal.msgSuccess('保存成功')
      })
    },
    /** 生成代码 */
    handleGenCode() {
      const tableName = this.info.tableName
      genCode(tableName).then(res => {
        this.$modal.msgSuccess('生成成功')
      })
    },
    /** 预览代码 */
    handlePreview(tableId) {
      // 如果没有传入tableId，则使用当前表的ID
      const id = tableId || this.info.tableId;
      if (!id) {
        this.$modal.msgError("表信息不存在");
        return;
      }
      previewTable(id).then(response => {
        this.preview.data = response.data;
        this.preview.open = true;
        this.preview.activeName = "domain.java";
      }).catch(error => {
        console.error("预览代码失败:", error);
        this.$modal.msgError("预览代码失败，请检查控制台错误信息");
      });
    },
    /** 高亮显示 */
    highlightedCode(code, key) {
      const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
      var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      const result = hljs.highlight(language, code || "", true);
      return result.value || '&nbsp;';
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    /** 处理预览数据 */
    handlePreviewData(data) {
      if (data && data.data) {
        this.preview.data = data.data;
        this.preview.open = true;
        this.preview.activeName = "domain.java";
      } else {
        this.$modal.msgError("预览数据格式错误");
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.gen-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.tab-container {
  margin-top: 20px;
}

.tab-nav {
  display: flex;
  margin-bottom: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s;
  margin: 0 5px;
  position: relative;
  overflow: hidden;
  
  &:hover {
    background: rgba(64, 158, 255, 0.08);
  }
  
  &.active {
    background: linear-gradient(135deg, #409EFF, #36D1DC);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    
    .tab-icon, .tab-text {
      color: white;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 30px;
      height: 3px;
      background: #fff;
      border-radius: 3px;
    }
  }
}

.tab-icon {
  margin-bottom: 8px;
  
  i {
    font-size: 24px;
    color: #606266;
  }
}

.tab-text {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

/* 预览对话框样式 */
.scrollbar {
  height: 85vh;
  overflow: hidden;
}

.scrollbar .el-tabs__content {
  overflow: auto;
  height: calc(85vh - 100px);
}

.scrollbar pre {
  margin: 15px 0;
  padding: 0;
}

.scrollbar code {
  padding: 20px;
  border-radius: 5px;
  overflow-x: auto;
  display: block;
}
</style> 